package com.FH.applyFrom.work_week_plan;

import com.FH.applyFrom.work_week_plan_detail.ExportWeekPlanDetialDTO;
import com.FH.applyFrom.work_week_plan_detail.WorkWeekPlanDetailPullDTO;
import com.FH.applyFrom.work_week_plan_detail.WorkWeekPlanDetailResource;
import com.FH.applyFrom.work_week_plan_detail.WorkWeekPlanDetailShowDTO;
import com.FH.organization.Attachment.AttachmentPullDTO;
import com.FH.organization.department.DepartmentResource;
import com.FH.organization.department.DepartmentShowDTO;
import com.FH.util.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/11/22 0022.
 */
@Stateless
public class WorkWeekPlanDAOImpl extends AccessDB implements WorkWeekPlanDAO {

    @Inject
    DepartmentResource departmentResource;

    @Inject
    WorkWeekPlanDetailResource workWeekPlanDetailResource;



    /**
     * 周计划查询
     *
     * @param search
     * @param page
     * @param size
     */
    @Override
    public ResultDTO getWorkWeekPlanInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(search);

            String sqlexit = "select count(1) from work_week_plan where 1=1";

            String sql_e = "";//查询是否存在sql组合
            String sql_w = "";//查询sql组合
            String sql_page;//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size;
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size;
            }
            if (json.has("work_week_plan_id")) {

                if(null != json.getString("work_week_plan_id").toString() && !json.getString("work_week_plan_id").toString().isEmpty() ){
                    sql_w += " and w.work_week_plan_id = '" + json.getString("work_week_plan_id").toString() + "'";
                    sql_e += " and work_week_plan_id = '" + json.getString("work_week_plan_id") + "'";
                }

            }
            if (json.has("organization_id")) {
                if(null != json.getString("organization_id").toString() && !json.getString("organization_id").toString().isEmpty() ){
                    sql_w += " and w.organization_id = '" + json.getString("organization_id") + "'";
                    sql_e += " and organization_id = '" + json.getString("organization_id") + "'";
                }

            }
            if (json.has("organization_name")) {
                if(null != json.getString("organization_name").toString() && !json.getString("organization_name").toString().isEmpty() ){
                    sql_w += " and o.organization_name = '" + json.getString("organization_name") + "'";
                    sql_e += " and organization_name = '" + json.getString("organization_name") + "'";
                }
            }
            if (json.has("start_time")) {
                if(null != json.getString("start_time").toString() && !json.getString("start_time").toString().isEmpty() ){
                    sql_w += " and w.start_time >= '" + json.getString("start_time") + "'";
                    sql_e += " and start_time >= '" + json.getString("start_time") + "'";
                }

            }
            if (json.has("end_time")) {
                if(null != json.getString("end_time").toString() && !json.getString("end_time").toString().isEmpty() ){
                    sql_w += " and w.end_time <= '" + json.getString("end_time") + "'";
                    sql_e += " and end_time <= '" + json.getString("end_time") + "'";
                }

            }

            String sql_ok = sqlexit + sql_e;
            String existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();
            List<WorkWeekPlanShowDTO> result = new ArrayList<WorkWeekPlanShowDTO>();

            if (!existName.equals("0")) {
                String sql = "select w.work_week_plan_id,w.organization_id,o.organization_name,w.start_time,w.end_time," +
                        "w.create_time,w.update_time " +
                        "from work_week_plan w " +
                        "LEFT JOIN organization o " +
                        "ON o.organization_id = w.organization_id " +
                        "where 1=1 "
                        + sql_w + sql_page;
                seresult = this.getReportingTo(sql);

                for (int i = 0; i < seresult.size(); i++) {
                    WorkWeekPlanShowDTO workWeekPlanShowDTO = new WorkWeekPlanShowDTO();

                    workWeekPlanShowDTO.setWork_week_plan_id(seresult.get(i)[1]);
                    workWeekPlanShowDTO.setOrganization_id(seresult.get(i)[2]);
                    workWeekPlanShowDTO.setOrganization_name(seresult.get(i)[3]);
                    workWeekPlanShowDTO.setStart_time(seresult.get(i)[4]);
                    workWeekPlanShowDTO.setEnd_time(seresult.get(i)[5]);
                    workWeekPlanShowDTO.setCreate_time(seresult.get(i)[6]);
                    workWeekPlanShowDTO.setUpdate_time(seresult.get(i)[7]);

                    ResultDTO organization = null, plans = null;

                    //部门信息
                    if (null != seresult.get(i)[2] && !"".equals(seresult.get(i)[2])) {
                        organization = departmentResource.getDepartmentInfo("{organization_id:" + seresult.get(i)[2] + "}", "1", "1");
                        workWeekPlanShowDTO.setDepartment(organization.getValues());
                    }

                    //计划列表
                    if (null != seresult.get(i)[1] && !"".equals(seresult.get(i)[1])) {
                        plans = workWeekPlanDetailResource.getWorkWeekPlanDetailInfo("{work_week_plan_id:" + seresult.get(i)[1] + "}", "1", "999");
                        workWeekPlanShowDTO.setWork_week_plan_list(plans.getValues());
                    }

                    result.add(workWeekPlanShowDTO);
                }
                if (result.size() != 0) {
                    resultDTO.setStatus("90000");
                    resultDTO.setDescritpion(warnSrc.get_success);
                } else {
                    resultDTO.setStatus("90001");
                    resultDTO.setDescritpion(warnSrc.get_fail);
                }
                resultDTO.setStr(result.size() + "");
                resultDTO.setValues(result);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
                resultDTO.setStr("该部门暂无周计划");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    /**
     * 周计划添加
     *
     * @param workWeekPlanPullDTO
     */
    @Override
    public ResultDTO addWorkWeekPlanInfo(WorkWeekPlanPullDTO workWeekPlanPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

        /*
         * 判断此信息是否已存在
         * 若存在,进行更新
         * 如不存在,执行add方法
         */
        String work_week_plan_id = workWeekPlanPullDTO.getWork_week_plan_id();
        if (null != work_week_plan_id && !"".equals(work_week_plan_id)) {

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            String judgeAdd = "select count(1) from work_week_plan where work_week_plan_id='" + work_week_plan_id + "'" +
                    " and (start_time > '" + df.format(new Date()) + "' or (start_time < '" +  df.format(new Date()) + "' and end_time > '" +
                    df.format(new Date()) + "'))";
            String exist = this.getReportingToOne(judgeAdd);
            if(Integer.parseInt(exist) > 0){

                //删除子项
                String delete_detail = "delete from work_week_plan_detail where work_week_plan_id = '" + workWeekPlanPullDTO.getWork_week_plan_id() + "'";
                addReportingTo(delete_detail);

                return updateWorkWeekPlanInfo(workWeekPlanPullDTO);
            }
        }

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        List<DepartmentShowDTO> org = departmentResource.getDepartmentInfo("{organization_id:" + workWeekPlanPullDTO.getOrganization_id() + "}", "1", "1").getValues();
        String organization_name = org.get(0).getOrganization_name();
        String insert = "insert into work_week_plan (work_week_plan_id,organization_id,start_time,end_time,create_time,update_time)" +
                " values ('" + uuid + "','" + workWeekPlanPullDTO.getOrganization_id() + "','" +
                workWeekPlanPullDTO.getStart_time() + "','" + workWeekPlanPullDTO.getEnd_time() + "','" + time + "','" + time + "')";
        int result = addReportingTo(insert);


        //添加或更新详细计划
        List<WorkWeekPlanDetailPullDTO> work_week_plan_list = workWeekPlanPullDTO.getWork_week_plan_list();

        if (null != work_week_plan_list) {

            for (int i = 0; i < work_week_plan_list.size(); i++) {

                WorkWeekPlanDetailPullDTO workWeekPlanDetailPullDTO = new WorkWeekPlanDetailPullDTO();

                if (null != work_week_plan_list.get(i).getWork_week_plan_detail_id() && !"".equals(work_week_plan_list.get(i).getWork_week_plan_detail_id().trim())) {
                    workWeekPlanDetailPullDTO.setWork_week_plan_detail_id(work_week_plan_list.get(i).getWork_week_plan_detail_id());
                }
                workWeekPlanDetailPullDTO.setWork_week_plan_id(uuid);
                if (null != work_week_plan_list.get(i).getWeek_date() && !"".equals(work_week_plan_list.get(i).getWeek_date().trim())) {
                    workWeekPlanDetailPullDTO.setWeek_date(work_week_plan_list.get(i).getWeek_date());
                }
                if (null != work_week_plan_list.get(i).getYear_date() && !"".equals(work_week_plan_list.get(i).getYear_date().trim())) {
                    workWeekPlanDetailPullDTO.setYear_date(work_week_plan_list.get(i).getYear_date());
                }
                if (null != work_week_plan_list.get(i).getAm_plan() && !"".equals(work_week_plan_list.get(i).getAm_plan().trim())) {
                    workWeekPlanDetailPullDTO.setAm_plan(work_week_plan_list.get(i).getAm_plan());
                }
                if (null != work_week_plan_list.get(i).getPm_plan() && !"".equals(work_week_plan_list.get(i).getPm_plan().trim())) {
                    workWeekPlanDetailPullDTO.setPm_plan(work_week_plan_list.get(i).getPm_plan());
                }

                workWeekPlanDetailResource.addWorkWeekPlanDetailInfo(workWeekPlanDetailPullDTO);
            }
        }

        if (result != 0) {
            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }

    /**
     * 周计划修改
     *
     * @param workWeekPlanPullDTO
     */
    @Override
    public ResultDTO updateWorkWeekPlanInfo(WorkWeekPlanPullDTO workWeekPlanPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

        //更新sql语句
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        String update = "update work_week_plan set update_time ='" + time + "'";

        if (null != workWeekPlanPullDTO.getOrganization_id() && !"".equals(workWeekPlanPullDTO.getOrganization_id())) {
            update += ",organization_id ='" + workWeekPlanPullDTO.getOrganization_id() + "'";
//            List<DepartmentShowDTO> org = departmentResource.getDepartmentInfo("{organization_id:" + workWeekPlanPullDTO.getOrganization_id() + "}", "1", "1").getValues();
//            String organization_name = org.get(0).getOrganization_name();
//            update += ",organization_name ='" + organization_name + "'";
        }
        if (null != workWeekPlanPullDTO.getStart_time() && !"".equals(workWeekPlanPullDTO.getStart_time())) {
            update += ",start_time ='" + workWeekPlanPullDTO.getStart_time() + "'";
        }
        if (null != workWeekPlanPullDTO.getEnd_time() && !"".equals(workWeekPlanPullDTO.getEnd_time())) {
            update += ",end_time ='" + workWeekPlanPullDTO.getEnd_time() + "'";
        }

        update += " where work_week_plan_id = '" + workWeekPlanPullDTO.getWork_week_plan_id() + "'";

        int result = addReportingTo(update);

        //删除子项
        String delete_detail = "delete from work_week_plan_detail where work_week_plan_id = '" + workWeekPlanPullDTO.getWork_week_plan_id() + "'";
        addReportingTo(delete_detail);
        //添加或更新详细计划
        List<WorkWeekPlanDetailPullDTO> work_week_plan_list = workWeekPlanPullDTO.getWork_week_plan_list();
        if (null != work_week_plan_list) {
            for (int i = 0; i < work_week_plan_list.size(); i++) {

                WorkWeekPlanDetailPullDTO workWeekPlanDetailPullDTO = new WorkWeekPlanDetailPullDTO();

                if (null != work_week_plan_list.get(i).getWork_week_plan_detail_id() && !"".equals(work_week_plan_list.get(i).getWork_week_plan_detail_id().trim())) {
                    workWeekPlanDetailPullDTO.setWork_week_plan_detail_id(work_week_plan_list.get(i).getWork_week_plan_detail_id());
                }
                workWeekPlanDetailPullDTO.setWork_week_plan_id(workWeekPlanPullDTO.getWork_week_plan_id());
                if (null != work_week_plan_list.get(i).getWeek_date() && !"".equals(work_week_plan_list.get(i).getWeek_date().trim())) {
                    workWeekPlanDetailPullDTO.setWeek_date(work_week_plan_list.get(i).getWeek_date());
                }
                if (null != work_week_plan_list.get(i).getYear_date() && !"".equals(work_week_plan_list.get(i).getYear_date().trim())) {
                    workWeekPlanDetailPullDTO.setYear_date(work_week_plan_list.get(i).getYear_date());
                }
                if (null != work_week_plan_list.get(i).getAm_plan() && !"".equals(work_week_plan_list.get(i).getAm_plan().trim())) {
                    workWeekPlanDetailPullDTO.setAm_plan(work_week_plan_list.get(i).getAm_plan());
                }
                if (null != work_week_plan_list.get(i).getPm_plan() && !"".equals(work_week_plan_list.get(i).getPm_plan().trim())) {
                    workWeekPlanDetailPullDTO.setPm_plan(work_week_plan_list.get(i).getPm_plan());
                }

                workWeekPlanDetailResource.addWorkWeekPlanDetailInfo(workWeekPlanDetailPullDTO);
            }
        }
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(workWeekPlanPullDTO.getWork_week_plan_id());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }

    /**
     * 周计划删除
     *
     * @param workWeekPlanPullDTO
     */
    @Override
    public ResultDTO deleteWorkWeekPlanInfo(WorkWeekPlanPullDTO workWeekPlanPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

        //判断是否存在
        String sql = "select count(1) from work_week_plan where work_week_plan_id = '" + workWeekPlanPullDTO.getWork_week_plan_id() + "'";
        String exist = getReportingToOne(sql);

        int result = 0;
        int result_detail = 0;
        if (!exist.equals("0")) {
            String delete = "delete from work_week_plan where work_week_plan_id = '" + workWeekPlanPullDTO.getWork_week_plan_id() + "'";
            String delete_detail = "delete from work_week_plan_detail where work_week_plan_id = '" + workWeekPlanPullDTO.getWork_week_plan_id() + "'";
            result = addReportingTo(delete);
            result_detail = addReportingTo(delete_detail);
        }
        // 判断SQl是否执行成功
        if (result != 0 && result_detail != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

    /**
     * 计划表格上传
     *
     * @param attachmentPullDTO
     */
    @Override
    public ResultDTO uploadExcel(AttachmentPullDTO attachmentPullDTO) {
        ResultDTO resultDTO = new ResultDTO();

        String[] file_path = this.getImage_path();
        String file_pathAddr = file_path[1];//服务器项目目录地址
        //获取配置地址
        String fileDirct = file_pathAddr + "/WeekPlan/upload";
        File f = new File(fileDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        String filePath = fileDirct + "/" + attachmentPullDTO.getFile_name();
        //base64字符串保存为文件
        boolean headImg = FileProcess.GenerateImage(attachmentPullDTO.getFile_stream(), filePath);
        FileProcess.newlog("执行文件储存方法，储存文件地址：" + filePath + " 方法返回：" + headImg);

        if (headImg) {
            WorkWeekPlanPullDTO workWeekPlanPullDTO = new WorkWeekPlanPullDTO();
            List<WorkWeekPlanDetailPullDTO> list = new ArrayList<WorkWeekPlanDetailPullDTO>();
            PoiExcelHelper helper = new PoiExcel2k7Helper();
            // 读取excel文件数据
            ArrayList<ArrayList<String>> dataList = helper.readExcel(filePath, 0, "1-");


            String org_id = dataList.get(0).get(1);
            String org_name = dataList.get(2).get(0);

            workWeekPlanPullDTO.setOrganization_id(org_id);
            workWeekPlanPullDTO.setStart_time(attachmentPullDTO.getStarttime());
            workWeekPlanPullDTO.setEnd_time(attachmentPullDTO.getEndtime());

            workWeekPlanPullDTO.setWork_week_plan_id(dataList.get(0).get(3));
            String start_date = dataList.get(0).get(2);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 2; i < dataList.size(); i++) {
                ArrayList<String> data = dataList.get(i);
                WorkWeekPlanDetailPullDTO workWeekPlanDetailPullDTO = new WorkWeekPlanDetailPullDTO();
                workWeekPlanDetailPullDTO.setWeek_date(data.get(1));

                Date date = null;
                try {
                    date = sdf.parse(start_date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                c.add(Calendar.DAY_OF_MONTH, i - 2);
                workWeekPlanDetailPullDTO.setYear_date(sdf.format(c.getTime()));
                workWeekPlanDetailPullDTO.setAm_plan(data.get(2));
                workWeekPlanDetailPullDTO.setPm_plan(data.get(3));

                list.add(workWeekPlanDetailPullDTO);
            }
            workWeekPlanPullDTO.setWork_week_plan_list(list);
            ResultDTO result = addWorkWeekPlanInfo(workWeekPlanPullDTO);
            if (result.getStr() != null) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setStr(result.getStr());
            ResultDTO resultDTO1 = getWorkWeekPlanInfo("{work_week_plan_id:" + result.getStr() + "}", "1", "1");
            resultDTO.setValues(resultDTO1.getValues());
        }
        return resultDTO;
    }

    /**
     * 计划表格下载
     *
     * @param org_id,start_time,end_time
     */
    @Override
    public ResultDTO downloadExcel(String org_id, String start_time, String end_time) {

        ResultDTO resultDTO = new ResultDTO();

        List<WorkWeekPlanShowDTO> weekPlanShowDTO = getWorkWeekPlanInfo("{organization_id:" + org_id + ",start_time:" + start_time + ",end_time:" + end_time + "}", "1", "999").getValues();

        String addr = "";
        String[] file_path = this.getImage_path();
        String file_pathAddr = file_path[1];//服务器项目目录地址
        String file_pathSerAddr = file_path[2];//文件访问地址
        if (null != weekPlanShowDTO) {
            String org_name = weekPlanShowDTO.get(0).getOrganization_name();
            addr = file_pathSerAddr + "/WeekPlan/download/" + start_time + "至" + end_time + org_name + "工作计划表.xlsx";// 文件名
            resultDTO.setStr(addr);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("下载成功");
//            return resultDTO;
        }

        // 第一步，创建一个webbook，对应一个Excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet("工作周计划表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        XSSFRow row0 = sheet.createRow((int) 0);
        XSSFRow row1 = sheet.createRow((int) 1);
        //设置表头样式
        XSSFFont font = wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        style.setFont(font);
        //单元格内自动换行
        style.setWrapText(true);

        XSSFCell cell = row0.createCell(0);
        cell.setCellValue(start_time + "至" + end_time + "周工作计划");
        cell.setCellStyle(style);

        cell = row1.createCell(0);
        cell.setCellValue("部门");
        cell.setCellStyle(style);
        cell = row1.createCell(1);
        cell.setCellValue("");
        cell.setCellStyle(style);
        cell = row1.createCell(2);
        cell.setCellValue("上午");
        cell.setCellStyle(style);
        cell = row1.createCell(3);
        cell.setCellValue("下午");
        cell.setCellStyle(style);

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到

        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        sheet.addMergedRegion(new CellRangeAddress(2, 8, 0, 0));

        WorkWeekPlanPullDTO workWeekPlanPullDTO = new WorkWeekPlanPullDTO();

        workWeekPlanPullDTO.setOrganization_id(org_id);
        workWeekPlanPullDTO.setStart_time(start_time);
        workWeekPlanPullDTO.setEnd_time(end_time);

//        List<WorkWeekPlanDetailPullDTO> weekPlanDetailPullDTOList = new ArrayList<WorkWeekPlanDetailPullDTO>();

        List<DepartmentShowDTO> org = departmentResource.getDepartmentInfo("{organization_id:" + org_id + "}", "1", "1").getValues();
        String org_name = org.get(0).getOrganization_name();

        for (int i = 0; i < 7; i++) {
            XSSFRow row = sheet.createRow(i + 2);
//            WorkWeekPlanDetailPullDTO workWeekPlanDetailPullDTO = new WorkWeekPlanDetailPullDTO();
            if (i == 0) {
                row.createCell(0).setCellValue(org_name);
                row.createCell(1).setCellValue("星期一");
//                workWeekPlanDetailPullDTO.setWeek_date("星期一");
            }
            if (i == 1) {
                row.createCell(1).setCellValue("星期二");
//                workWeekPlanDetailPullDTO.setWeek_date("星期二");
            }
            if (i == 2) {
                row.createCell(1).setCellValue("星期三");
//                workWeekPlanDetailPullDTO.setWeek_date("星期三");
            }
            if (i == 3) {
                row.createCell(1).setCellValue("星期四");
//                workWeekPlanDetailPullDTO.setWeek_date("星期四");
            }
            if (i == 4) {
                row.createCell(1).setCellValue("星期五");
//                workWeekPlanDetailPullDTO.setWeek_date("星期五");
            }
            if (i == 5) {
                row.createCell(1).setCellValue("星期六");
//                workWeekPlanDetailPullDTO.setWeek_date("星期六");
            }
            if (i == 6) {
                row.createCell(1).setCellValue("星期日");
//                workWeekPlanDetailPullDTO.setWeek_date("星期日");
            }
            row.createCell(2).setCellValue("");
            row.createCell(3).setCellValue("");
//            weekPlanDetailPullDTOList.add(workWeekPlanDetailPullDTO);
        }

//        workWeekPlanPullDTO.setWork_week_plan_list(weekPlanDetailPullDTOList);

        ResultDTO work_result = addWorkWeekPlanInfo(workWeekPlanPullDTO);
        cell = row0.createCell(1);
        cell.setCellValue(org_id);
        cell.setCellStyle(style);
        cell = row0.createCell(2);
        cell.setCellValue(start_time);
        cell.setCellStyle(style);
        cell = row0.createCell(3);
        cell.setCellValue(work_result.getStr());
        cell.setCellStyle(style);

        //下载excel
        Response response = null;

        try {
            //缓存文件到服务器本地
            String fileDirct = file_pathAddr + "/WeekPlan/download";
            File f = new File(fileDirct);
            if (!f.exists()) {
                f.mkdirs();
                f.setWritable(true, false);
            }
            //
            String fileName = start_time + "至" + end_time + org_name + "工作计划表.xlsx";// 文件名
            FileOutputStream fout = new FileOutputStream(fileDirct + "/" + fileName);
            wb.write(fout);
            fout.close();
            File file = new File(fileDirct + "/" + fileName);
            long fileLength = file.length();
            Response.ResponseBuilder responseBuilder = Response.ok(file);
            responseBuilder.type("application/x-msdownload");
            responseBuilder.header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            responseBuilder.header("Content-Length", Long.toString(fileLength));
            response = responseBuilder.build();
            addr = file_pathSerAddr + "/WeekPlan/download/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultDTO.setStr(addr);
        resultDTO.setStatus("90000");
        resultDTO.setDescritpion("下载成功");
        return resultDTO;
    }





    /**
     * 根据日期导出全部部门计划
     *
     * @param start_time,end_time
     */
    @Override
    public ResultDTO downloadPlanExcel(String start_time, String end_time) {

        ResultDTO resultDTO = new ResultDTO();

        // 第一步，创建一个webbook，对应一个Excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet("工作周计划表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        XSSFRow row0 = sheet.createRow((int) 0);
        XSSFRow row1 = sheet.createRow((int) 1);
        //设置表头样式
        XSSFFont font = wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        style.setFont(font);
        //单元格内自动换行
        style.setWrapText(true);

        sheet.setColumnWidth(2,10000);
        sheet.setColumnWidth(3,10000);

        XSSFCell cell = row0.createCell(0);
        cell.setCellValue(start_time + "至" + end_time + "周工作计划");
        cell.setCellStyle(style);

        cell = row1.createCell(0);
        cell.setCellValue("部门");
        cell.setCellStyle(style);
        cell = row1.createCell(1);
        cell.setCellValue("");
        cell.setCellStyle(style);
        cell = row1.createCell(2);
        cell.setCellValue("上午");
        cell.setCellStyle(style);
        cell = row1.createCell(3);
        cell.setCellValue("下午");
        cell.setCellStyle(style);

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到

        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

        List<WorkWeekPlanShowDTO> weekPlanShowDTOList = getWorkWeekPlanInfo("{start_time:" + start_time + ",end_time:" + end_time + "}", "1", "999").getValues();

        for(int i=0;i<weekPlanShowDTOList.size();i++){
            List<WorkWeekPlanDetailShowDTO> weekPlanDetailShowDTOList = weekPlanShowDTOList.get(i).getWork_week_plan_list();
            for(int j=0;j<weekPlanDetailShowDTOList.size();j++){
                WorkWeekPlanDetailShowDTO workWeekPlanDetailShowDTO = weekPlanDetailShowDTOList.get(j);
                XSSFRow row = sheet.createRow((i)*7 + j + 2);
                if (j == 0) {
                    row.createCell(0).setCellValue(weekPlanShowDTOList.get(i).getOrganization_name());
                }
                row.createCell(1).setCellValue(workWeekPlanDetailShowDTO.getWeek_date());
                row.createCell(2).setCellValue(workWeekPlanDetailShowDTO.getAm_plan());
                row.createCell(3).setCellValue(workWeekPlanDetailShowDTO.getPm_plan());
            }
            sheet.addMergedRegion(new CellRangeAddress(i*7+2, (i+1)*7+1, 0, 0));
        }

        //下载excel
        Response response = null;

        String addr = "";
        try {
            String[] file_path = this.getImage_path();
            String file_pathAddr = file_path[1];//服务器项目目录地址
            String file_pathSerAddr = file_path[2];//文件访问地址
            //缓存文件到服务器本地
            String fileDirct = file_pathAddr + "/WeekPlan/download";
            File f = new File(fileDirct);
            if (!f.exists()) {
                f.mkdirs();
                f.setWritable(true, false);
            }
            //
            String fileName = start_time + "至" + end_time + "周工作计划表.xlsx";// 文件名
            FileOutputStream fout = new FileOutputStream(fileDirct + "/" + fileName);
            wb.write(fout);
            fout.close();
            File file = new File(fileDirct + "/" + fileName);
            long fileLength = file.length();
            Response.ResponseBuilder responseBuilder = Response.ok(file);
            responseBuilder.type("application/x-msdownload");
            responseBuilder.header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            responseBuilder.header("Content-Length", Long.toString(fileLength));
            response = responseBuilder.build();
            addr = file_pathSerAddr + "/WeekPlan/download/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultDTO.setStr(addr);
        resultDTO.setStatus("90000");
        resultDTO.setDescritpion("下载成功");
        return resultDTO;
    }

    @Override
    public ResultDTO poiExcel(AttachmentPullDTO attachmentPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

        String[] file_path = this.getImage_path();
        String file_pathAddr = file_path[1];//服务器项目目录地址
        //获取配置地址
        String fileDirct = file_pathAddr + "/WeekPlan/download";
        File f = new File(fileDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        String filePath = fileDirct + "/" + attachmentPullDTO.getFile_name();
        //base64字符串保存为文件
        boolean headImg = FileProcess.GenerateImage(attachmentPullDTO.getFile_stream(), filePath);
        FileProcess.newlog("执行文件储存方法，储存文件地址：" + filePath + " 方法返回：" + headImg);

        if(headImg){
            List<ExportWeekPlanDetialDTO> result = new ArrayList<ExportWeekPlanDetialDTO>();
            PoiExcelHelper helper = new PoiExcel2k7Helper();
            // 读取excel文件数据
            ArrayList<ArrayList<String>> dataList = helper.readExcel(filePath,0,"3-");
            for (int i=0;i<dataList.size();i++){
                ArrayList<String> data = dataList.get(i);
                ExportWeekPlanDetialDTO exportWeekPlanDetialDTO = new ExportWeekPlanDetialDTO();
                exportWeekPlanDetialDTO.setOrganization_name(data.get(0)  == null ? "" : data.get(0));
                exportWeekPlanDetialDTO.setWeek_date(data.get(1)  == null ? "" : data.get(1));
                exportWeekPlanDetialDTO.setAm_plan(data.get(2)  == null ? "" : data.get(2));
                exportWeekPlanDetialDTO.setPm_plan(data.get(3)  == null ? "" : data.get(3));
//                exportWeekPlanDetialDTO.setYear_date(data.get(4)  == null ? "" : data.get(4));

                result.add(exportWeekPlanDetialDTO);
            }

            if (result.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setStr(result.size() + "");
            resultDTO.setValues(result);
        }

        return resultDTO;
    }
}